import * as d3 from "d3"
export class WaveView {
  currentX = 0 //当前X坐标
  currentY = 0 //当前Y坐标
  lastX = 0 //上次X坐标
  lastY = 0 //上次Y坐标
  clearGap = 15 // 橡皮檫宽度

  width = 0
  height = 0
  ctx
  queue = [] // 队列
  strokeStyle = "#0f0" //线条默认颜色

  step = 0 // 每次画几个点

  frameSize = 0 //1秒多少个点
  drawInterval = 20
  loopTimer = null
  xScale
  yScale
  isHidden = false
  /**
   * @param el DOM
   * @param strokeStyle 线的样式
   */
  constructor({ el, strokeStyle }) {
    const canvas = d3
      .select(el)
      .append("canvas")
      .attr("width", 430)
      .attr("height", 152)
      .node()
    this.width = 430
    this.height = 152
    this.ctx = canvas.getContext("2d")
    this.lastY = this.height / 2

    this.strokeStyle = strokeStyle

    this.xScale = d3.scaleLinear().domain([0, 6000]).range([0, 430])
    this.yScale = d3.scaleLinear().domain([-6000, 6000]).range([152, 30])

    document.addEventListener("visibilitychange",  ()=> {
      if (document.hidden) {
        // 页面已经切换到后台
        console.log("切换到后台")
        this.isHidden = true
      } else {
        // 页面已经切换到前台
        console.log("切换到前台")
        this.isHidden = false
      }
    })
  }

  draw = () => {
    // 更新心电图
    this.ctx.beginPath()
    this.ctx.lineWidth = 1
    this.ctx.strokeStyle = this.strokeStyle
    this.ctx.clearRect(this.lastX, 0, this.clearGap, this.height)
    for (let i = 0; i < this.step; i++) {
      if (this.queue.length === 0) {
        this.currentY = this.height / 2
      } else {
        this.currentY = this.yScale(this.queue.shift())
      }
      this.ctx.moveTo(this.lastX, this.lastY)
      this.ctx.lineTo(this.currentX, this.currentY)
      this.lastX = this.currentX
      this.lastY = this.currentY

      this.currentX += 0.1

      if (this.currentX >= this.width) {
        this.currentX = 0
        this.lastX = 0
      }
    }
    this.ctx.stroke()
  }
  loop = () => {
    if (this.queue.length) {
      this.draw()
      this.loopTimer = setTimeout(this.loop, this.drawInterval)
    } else {
      clearTimeout(this.loopTimer)
      this.loopTimer = null
    }
  }
  addData = (arr) => {
    if (!this.isHidden) {
      this.queue.push(...arr)
      this.frameSize = arr.length
      this.step = Math.floor((this.queue.length / 1000) * this.drawInterval)
      if (!this.loopTimer) {
        this.loop()
      }
    }
  }
  close = () => {
    this.queue = []
    clearTimeout(this.loopTimer)
    this.loopTimer = null
    this.ctx.clearRect(0, 0, this.width, this.height)
  }
}
